package com.erclab.internal.xpresso.security;

import java.util.HashMap;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.datavalidators.DataValidationError;
import com.erclab.internal.xpresso.exceptions.DirectoryException;
import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.formelements.FormElement;
import com.erclab.internal.xpresso.forms.Form;
import com.erclab.internal.xpresso.forms.FormHelper;

public class RegistrationFormHelper implements FormHelper {

	// TODO: Change this when Form Parameters are added
	protected String USERNAME_FIELD = "UserName";
	
	public void beforeFormCreation(Form theForm) throws FormException {
		if (theForm.getFormParameters().getAction().equals("update")){
			throw new FormException("Action not allowed in this form");
		}
	}

	public void afterFormCreation(Form theForm) throws FormException {
		
	}

	public void afterSubmission(Form theForm, HashMap keyValues)
			throws FormException, DataValidationError {
		
		User user = new User();
		String userName = getUserName(theForm, keyValues);
		user.setUserName(userName);
		try {
			Settings.getUserDirectory().loadUserBean(user);
		} catch (DirectoryException e) {
			throw new FormException("An error occurred while checking user directory: " + e);
		}
		if (user.getIdUser() != 0){
			throw new DataValidationError("The user name: " + userName + " is taken. Please choose another one");
		}

	}

	public void afterModification(Form form, HashMap keyValues)
			throws FormException, DataValidationError {
	
		String userName = getUserName(form, keyValues);
		User user = form.getFormParameters().getUser();
		user.setUserName(userName);
		try {
			Settings.getUserDirectory().loadUserBean(user);
		} catch (DirectoryException e) {
			throw new FormException("A Directory exception was generated: " + e);
		} 
	}

	private String getUserName(Form form, HashMap keyValues) {
		String userName = null;
		for (int i = 0; i < form.getFormElements().size(); i++){
			FormElement f = (FormElement)form.getFormElements().get(i);
			if (f.getDestinationColumn().equals(USERNAME_FIELD)){
				userName = ((String[])keyValues.get("Field" + f.getIdFormElement()))[0];
				break;
			}
		}
		return userName;
	}
}
